package com.tvunetworks.center.device.schedule;

import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.device.mapper.SyncTvuDeviceMapper;
import com.tvunetworks.center.device.service.DeviceGeoRecordService;
import com.tvunetworks.center.device.service.DeviceGeoService;
import com.tvunetworks.center.device.service.GridMetadataService;
import com.tvunetworks.center.device.service.MyDeviceService;
import com.tvunetworks.center.device.util.ThreadPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @program: tvucc-aggregator
 * @description: ReceiverCheckUDPSchedule
 * @author lebronchen
 * @create: 2020-07-22 16:06
 **/
@RestController
@RequestMapping("/schedule/device")
@Slf4j
public class DeviceJobSchedule {

    @Autowired
    private MyDeviceService myDeviceService;
    @Autowired
    private DeviceGeoService deviceGeoService;
    @Autowired
    private SyncPSSchedule syncPSSchedule;
    @Autowired
    private DeviceGeoRecordService deviceGeoRecordService;
    @Autowired
    private SyncTvuDeviceMapper syncTvuDeviceMapper;
    @Autowired
    private GridMetadataService metadataService;

    @Value("${tracking.clearHistoryDataTime}")
    private Long clearHistoryDataTime;

    /**
     * checkReceiverUDP
     * @return Result
     */
    @PostMapping("/checkReceiverUDP")
    public Result checkReceiverUDP(){
        ThreadPoolUtil.SERVICETHREADPOOL.execute(() -> myDeviceService.checkReceiverUDP());
        return ResultUtil.success();
    }

    /**
     *
     * @return Result
     */
    @PostMapping("/initDeviceGeo")
    public Result initDeviceGeo(){
        //任务执行时间过长，所以需要开线程去跑，保证job端正常返回
        String dd="{\"type\":\"HDMI\",\"format\":\"720p50\",\"delay\":\"2.0 s\",\"error\":0,\"quality\":28.5714,\"slotInfo\":[1,1,2,1,1,0,0,0,0,1,0,0,0,3],\"img\":\"http://blob.tvunetworks.com/t/3E3E1AED3A04C722?type=original&app=cc&0.8495558880567877\",\"voiceInfo\":{\"DB\":[-33,-30,-40,-40,-40,-40,-40,-40],\"RightDb\":-30,\"LeftDb\":-33}}";
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    log.error("initDeviceGeo start==="+System.currentTimeMillis());
                    deviceGeoService.initDeviceGeo();
                    log.error("initDeviceGeo end==="+System.currentTimeMillis());
                } catch (Exception e) {
                    log.error(e.toString(), e);
                    log.error("initDeviceGeo Exception==="+System.currentTimeMillis());
                }
            }
        }).start();
        return ResultUtil.success();
    }

    /**
     *
     * @return Result
     */
    @PostMapping("/syncPSSchedule")
    public Result syncPSSchedule(){
        //任务执行时间过长，所以需要开线程去跑，保证job端正常返回
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    log.error("syncPSSchedule start==="+System.currentTimeMillis());
//                    deviceGeoService.initDeviceGeo();
//                    SyncPSSchedule a = new SyncPSSchedule();
                    syncPSSchedule.syncPSSchedule();
                    log.error("syncPSSchedule end==="+System.currentTimeMillis());
                } catch (Exception e) {
                    log.error(e.toString(), e);
                    log.error("syncPSSchedule Exception==="+System.currentTimeMillis());
                }
            }
        }).start();
        return ResultUtil.success();
    }

    /**
     *
     * @return Result
     */
    @PostMapping("/clearGeoRecordHistoryData")
    public Result clearGeoRecordHistoryData(){
        //任务执清楚Device geo record 历史记录，默认是90天之前
        new Thread(new Runnable() {
            @Override
            public void run() {
                Long nowTime = System.currentTimeMillis();
                Long clearTime = nowTime -clearHistoryDataTime*24*60*60*1000;
                try {
                    log.error("clearGeoRecordHistoryData start==="+System.currentTimeMillis());
                    log.error("clearGeoRecordHistoryData clearTime==="+clearTime);

                    deviceGeoRecordService.clearGeoRecordHistoryData(String.valueOf(clearTime));
                    log.error("clearGeoRecordHistoryData end==="+System.currentTimeMillis());
                } catch (Exception e) {
                    log.error(e.toString(), e);
                    log.error("clearGeoRecordHistoryData Exception==="+System.currentTimeMillis());
                }
            }
        }).start();
        return ResultUtil.success();
    }

    /**
     *
     * @return Result
     */
    @PostMapping("/syncTvuDeviceTask")
    public Result syncTvuDeviceTask(){
        //1.查询出token device表中存在而tvu_device表不存在的数据
        List<String> notExistTvuDeviceData = syncTvuDeviceMapper.getNotExistTvuDeviceData();
        if (CollectionUtils.isNotEmpty(notExistTvuDeviceData)){
            log.info(">>>>>>>>>>>>>>>>>get notExistTvuDeviceData size:{}",notExistTvuDeviceData.size());
        }
        if(notExistTvuDeviceData == null || notExistTvuDeviceData.size() == 0){
            return ResultUtil.success(0);
        }
        //2.取出peerId，判断sychdevice表是否存在，存在即更新，不存在，不做操作
        for(int i = 0 ; i < notExistTvuDeviceData.size() ; i++){
            String peerId = notExistTvuDeviceData.get(i);
            if(StringUtils.isBlank(peerId)){
                continue;
            }
            //3.查询sychdevice表
//			 int getSychdeviceData = syncTvuDeviceMapper.selectSychdeviceByPeerId(peerId);
//			 //不存在,不操作
//			 if(getSychdeviceData == 0){
//					log.error(">>>>>>>>>>>>>>>>>>>>>>>>synchdevice not exist peerId:{}",peerId);
//				 continue;
//			 }
            int updateFlag = syncTvuDeviceMapper.updateToTvuDevice(peerId);
            log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>synchdevice exists peerId:{} update",peerId);
            if(updateFlag == 0){
                log.info("peerId：{} update failed",peerId);
            }
            //线程休眠
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.error("InterruptedException is error",e);
            }
        }
        return ResultUtil.success(notExistTvuDeviceData.size());

    }

    /** 
    * @param   
    * @return com.tvunetworks.center.common.util.Result 
    * @author KevinLi
    * @date 12/7/2021 
    * @throws Exception if has error
    */
    @PostMapping("/synGridSlug")
    public Result synGridSlug() throws Exception{
        return ResultUtil.success(metadataService.synGridSlug());
    }
}
